<template>
  <BasicTable @register="attributeRegister" :data-source="shopGoodsStore.attributeList">
    <template #toolbar>
      <a-button type="primary" @click="handleAddAttributes">{{
        props.attributesSelect == 'many' ? '添加参数' : '添加属性'
      }}</a-button>
    </template>
    <template #expandedRowRender="{ record }">
      <div v-for="item in record.attr_vals" :key="item" class="mx-3 inline-block">
        <a-tag color="processing" closable @close.prevent="handleDeleteTag(record, item)">{{
          item
        }}</a-tag>
      </div>
      <div class="mx-3 inline-block">
        <a-button v-if="!record.editStatus" size="small" @click="handleAddTag(record)"
          ><PlusOutlined />新增标签</a-button
        >
        <a-input
          v-else
          size="small"
          :maxlength="30"
          style="width: 100px"
          ref="attributeInput"
          v-model:value="state.attributeValue"
          @press-enter="handleConfirm(record)"
          @blur="handleConfirm(record)"
        >
          <template #suffix>
            <a class="ml-2 text-red-500 hover:text-red-600" @click="handleCancel(record)">
              <CloseCircleFilled />
            </a>
          </template>
        </a-input>
      </div>
    </template>
    <template #operations="{ record }">
      <TableAction
        stopButtonPropagation
        :actions="[
          {
            label: '编辑',
            icon: 'ant-design:edit-outlined',
            onClick: handleEdit.bind(null, record),
            // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
          },
          {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            // auth: 'super', // 根据权限控制是否显示: 有权限，会显示
            popConfirm: {
              title: '是否删除？',
              confirm: handleDelete.bind(null, record),
            },
          },
        ]"
      />
    </template>
  </BasicTable>
</template>

<script lang="ts" setup>
  import { ref, nextTick, reactive } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { PlusOutlined, CloseCircleFilled } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import { useShopGoodsStore } from '/@/store/modules/shopGoodsStore';

  type stateModel = {
    attributeValue: string;
    attributeList: object[];
  };

  const props = defineProps({
    attributesSelect: String,
  });

  const emits = defineEmits(['handleAddAttributes', 'handleEdit']);

  const shopGoodsStore = useShopGoodsStore();

  const attributeInput: any = ref(null);

  const state: stateModel = reactive({
    attributeValue: '',
    attributeList: [],
  });

  const updateAttribute = async (params: Array<any>) => {
    const id = params[0];
    const attr_id = params[1];
    const attr_name = params[2];
    const attr_vals = params[3];
    const attr_sel: string | any = props.attributesSelect;
    try {
      const row = await shopGoodsStore.updateAttributes({
        id,
        attr_id,
        attr_name,
        attr_sel,
        attr_vals,
      });
      shopGoodsStore.attributeList = shopGoodsStore.attributeList.map((item: any) => {
        if (item.attr_id == row.attr_id) {
          item = row;
        }
        return item;
      });
      message.success('修改成功');
    } catch (error) {
      console.error(error);
    }
  };

  const handleDeleteTag = (record: any, item: any) => {
    let attr_vals: string | any;
    if (props.attributesSelect == 'many') {
      attr_vals = record.attr_vals.filter((listItem: any) => listItem != item).join(',');
    }
    if (props.attributesSelect == 'only') {
      attr_vals = record.attr_vals.filter((listItem: any) => listItem != item).join(' ');
    }
    updateAttribute([record.cat_id, record.attr_id, record.attr_name, attr_vals]);
  };

  const handleAddTag = async (record: any) => {
    record.editStatus = true;
    // 状态更新后聚焦
    await nextTick();
    attributeInput.value?.focus();
  };

  const handleConfirm = async (record: any) => {
    record.editStatus = false;
    if (!state.attributeValue) return;
    record.attr_vals.push(state.attributeValue);
    let attr_vals: string | any;
    if (props.attributesSelect == 'many') {
      attr_vals = record.attr_vals.join(',');
    }
    if (props.attributesSelect == 'only') {
      attr_vals = record.attr_vals.join(' ');
    }
    updateAttribute([record.cat_id, record.attr_id, record.attr_name, attr_vals]);
    state.attributeValue = '';
  };

  const handleDelete = async (record: any) => {
    const params = {
      id: record.cat_id,
      attrid: record.attr_id,
    };
    try {
      await shopGoodsStore.deleteAttributes({ ...params });
      message.success('删除成功');
      shopGoodsStore.attributeList = shopGoodsStore.attributeList.filter((item: any) => {
        return item.attr_id != record.attr_id;
      });
    } catch (error) {
      console.error(error);
    }
  };

  const handleAddAttributes = () => {
    emits('handleAddAttributes');
  };

  const handleEdit = (record: any) => {
    emits('handleEdit', record);
  };

  const handleCancel = (record: any) => {
    record.editStatus = false;
  };

  const [attributeRegister] = useTable({
    rowKey: (record: any) => {
      return record.attr_id;
    },
    columns: [
      {
        title: '属性名称',
        dataIndex: 'attr_name',
      },
    ],
    striped: true,
    bordered: true,
    pagination: false,
    showTableSetting: false,
    expandRowByClick: true,
    actionColumn: {
      title: '操作',
      dataIndex: 'operations',
      slots: { customRender: 'operations' },
    },
  });
</script>
